package Client;

import Message.AccountSendMessageInfo;
import utils.AccountSendMessageInfoFromOneList;
import utils.AccountSendMessageInfoList;
import utils.ReadWriteFileByAccountSendMessageInfoFromOneList;

import java.io.*;
import java.net.Socket;

/**
 * 该类应由登陆成功后的User类调用，一旦初始化该类就开始向服务端轮询有没有聊天消息发给当前用户，初始化该类需要当前用户的UserId
 * 调用该类的interruptThread方法即可停止轮询，即退出登录时应调用该方法
 * */
public class SendRequestsRegularlyToGetMessage implements Serializable{
    private User user;
    private ThreadHandleSendRequestsRegularlyToGetMessage threadHandleSendRequestsRegularlyToGetMessage;

    //退出登录的事件监听使用该方法
    public void interruptThread() {
        threadHandleSendRequestsRegularlyToGetMessage.interrupt();
    }

    public SendRequestsRegularlyToGetMessage(User user) throws IOException {
        this.user = user;
        threadHandleSendRequestsRegularlyToGetMessage = new ThreadHandleSendRequestsRegularlyToGetMessage(this.user);
        threadHandleSendRequestsRegularlyToGetMessage.start();
        System.out.println("当前共有"+(Thread.activeCount()-3)+"个用户线程");//本地作为服务端时要减去本地服务器线程的数量
    }

}

class ThreadHandleSendRequestsRegularlyToGetMessage extends Thread implements Serializable{
    private User user;

    public ThreadHandleSendRequestsRegularlyToGetMessage(User user){
        super("用户" + user.getUserId() + "的线程");
        this.user = user;
    }

    public String getUserId() {
        return user.getUserId();
    }

    public void run() {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println(this.getName()+"线程被中断");
                //处理中断逻辑
                break;
            } else {
                try {
                    Socket socket = new Socket(ServerInfo.SERVER_IP_ADDRESS, ServerInfo.SERVER_SENDREQUESTSREGULARLYTOGETMESSAGE_PORT);

                    OutputStream outputStream=socket.getOutputStream();//获取一个输出流，向服务端发送信息
                    PrintWriter printWriter=new PrintWriter(outputStream);//将输出流包装成打印流
                    printWriter.print(getUserId());//此处将当前用户的id发送给服务端
                    printWriter.flush();
                    socket.shutdownOutput();//关闭输出流

                    InputStream inputStream = socket.getInputStream();
                    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                    //下面这一行接收服务端返回的发送给当前用户的消息队列
                    AccountSendMessageInfoList accountSendMessageInfoList = (AccountSendMessageInfoList) objectInputStream.readObject();
                    user.setMessageList(accountSendMessageInfoList);
                    //关闭相应资源
                    outputStream.close();
                    printWriter.close();
                    inputStream.close();
                    objectInputStream.close();
                    socket.close();

                    /*int size = accountSendMessageInfoList.size();
                    if(size == 0){
                        System.out.println("没有人发消息给当前用户");
                    }else{
                        System.out.println("有"+size+"人发消息给当前用户");
                        *//**
                         * 这里初始化类来把聊天记录写入文件
                         * *//*
                        ReadWriteFileByAccountSendMessageInfoFromOneList readWriteFileByAccountSendMessageInfoFromOneList = new ReadWriteFileByAccountSendMessageInfoFromOneList();
                        for(int i=0;i<size;i++){
                            //获得来自同一个用户的所有消息
                            AccountSendMessageInfoFromOneList accountSendMessageInfoFromOneList = accountSendMessageInfoList.get(i);
                            int sizeOfAccountSendMessageInfoFromOneList = accountSendMessageInfoFromOneList.size();
                            String userIdInDatabaseFrom = accountSendMessageInfoFromOneList.get(0).getUserIdInDatabaseFrom();
                            String fileName = "From_"+userIdInDatabaseFrom + "_To_" +getUserId() + ".txt";
                            for (int j = 0; j < sizeOfAccountSendMessageInfoFromOneList; j++) {
                                //获得单条聊天记录对象
                                AccountSendMessageInfo message = accountSendMessageInfoFromOneList.get(j);
                                String messageInFile = message.getInfo();
                                System.out.println(i+" "+j+messageInFile);
                                readWriteFileByAccountSendMessageInfoFromOneList.writeInFile(fileName, messageInFile); //实现将该用户与某一人的聊天记录写入文件
                            }
                        }
                    }*/
                    //System.out.println("获取消息的线程没有中断");
                    sleep(1000);
                } catch (InterruptedException | IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
